package net.sunzc.yunlian.controller.entity;

import java.io.*;
import java.util.zip.ZipEntry;
import java.util.zip.ZipInputStream;
import java.util.zip.ZipOutputStream;

/**
 * Created by Sun on 2016/8/19.
 */
public class ZipCompresser {

    /**
     * Zip it
     */
    public static void zip(File[] files, String desFilePath, String comment) {
        byte[] buffer = new byte[1024];
        try {
            File destFile = new File(desFilePath);
            if (destFile.exists()) {
                destFile.delete();
            }
            FileOutputStream fos = new FileOutputStream(destFile);
            ZipOutputStream zos = new ZipOutputStream(fos);
            System.out.println("Output to Zip : " + destFile);
            for (File file : files) {
                System.out.println("File Added : " + file);
                ZipEntry ze = new ZipEntry(file.getName());
                ze.setComment(comment);
                zos.putNextEntry(ze);
                FileInputStream in = new FileInputStream(file);
                int len;
                while ((len = in.read(buffer)) > 0) {
                    zos.write(buffer, 0, len);
                }
                in.close();
            }
            zos.closeEntry();
            zos.close();
            System.out.println("Done");
        } catch (IOException ex) {
            ex.printStackTrace();
        }
    }

    /*
        * @param srcZipFile 需解压的文件名
        * @return  如果解压成功返回true
        */
    public boolean unzip(String srcZipFile, String destFilePath) {
        boolean isSuccessful = true;
        try {
            BufferedInputStream bis = new BufferedInputStream(new FileInputStream(srcZipFile));
            ZipInputStream zis = new ZipInputStream(bis);
            BufferedOutputStream bos;
            ZipEntry entry;
            while ((entry = zis.getNextEntry()) != null) {
                String entryName = entry.getName();
                bos = new BufferedOutputStream(new FileOutputStream(destFilePath));
                int b;
                while ((b = zis.read()) != -1) {
                    bos.write(b);
                }
                bos.flush();
                bos.close();
            }
            zis.close();
        } catch (IOException e) {
            isSuccessful = false;
        }
        return isSuccessful;
    }
}
